<?php

namespace App\Models\Common;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use DateTimeInterface;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;

abstract class CommonModel extends Model
{
    use SoftDeletes;
    protected $guarded = [];
    protected $hidden = ['password','deleted_at'];

    protected function serializeDate(DateTimeInterface $date) {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }

    /**
     * 关联关系取消蛇形命名
     * @param bool $val
     * @return bool
     * @Date 2021/1/9
     * @Author Guodongsheng
     */
    /*public static function isSnakeAttributes($val = true): bool {
        self::$snakeAttributes = $val;
        return self::$snakeAttributes;
    }*/

    /*public function __construct(array $attributes = []) {
        parent::__construct($attributes);
        self::isSnakeAttributes(false);
    }*/

    /*public function getQrUrlAttribute($value){
            return url($value);
      }*/

    public function getRecords(array $conditions){
        if(!isset($conditions['orderBy'])){
            $conditions['orderBy']['col'] = 'id';
            $conditions['orderBy']['sort'] = 'desc';
        }

        $records = $this->newQuery();
        if(isset($conditions['id'])){
            if(is_array($conditions['id'])){
                $conditions['id'] = array_filter($conditions['id']);
                //这一层判断必须有，当array_filter是一个空数组
                if(count($conditions['id'])>0){
                    $records = count($conditions['id'])>1?$records->whereIn('id',$conditions['id']):
                        $records->where('id',Arr::first($conditions['id']));
                }
            }
            else{
                $records = $records->where('id',$conditions['id']);
            }
        }

        if(!empty($conditions['password'])){
            $records = $records->where('password',$conditions['password']);
        }
        if(!empty($conditions['phone'])){
            $records = $records->where('phone',$conditions['phone']);
        }
        if(!empty($conditions['passport'])){
            $records = $records->where('passport',$conditions['passport']);
        }
        if(isset($conditions['pid'])){
            $records = $records->where('pid',$conditions['pid']);
        }
        if(isset($conditions['orderNumber'])){
            $records = $records->where('order_number',$conditions['orderNumber']);
        }
        if(!empty($conditions['name'])){
            $records = $records->where('name','like','%'.$conditions['name'].'%');
        }
        if(!empty($conditions['title'])){
            $records = $records->where('title','like','%'.$conditions['title'].'%');
        }
        if(!empty($conditions['fullName'])){
            $records = $records->where('full_name','like',"%".$conditions['fullName']."%");
        }
        if(!empty($conditions['lastName'])){
            $records = $records->where('last_name','like',"%".$conditions['lastName']."%");
        }
        if(!empty($conditions['firstName'])){
            $records = $records->where('first_name','like',"%".$conditions['firstName']."%");
        }
        if(!empty($conditions['wxName'])){
            $records = $records->where('wx_name','like','%'.$conditions['wxName'].'%');
        }
        if(!empty($conditions['nickName'])){
            $records = $records->where('nick_name','like','%'.$conditions['nickName'].'%');
        }
        if(!empty($conditions['email'])){
            $records = $records->where('email',$conditions['email']);
        }
        if(!empty($conditions['createdAtDate'])){
            if(is_array($conditions['createdAtDate'])){
                $records = $records->whereDate('created_at','>=',$conditions['createdAtDate'][0])
                    ->whereDate('created_at','<=',$conditions['createdAtDate'][1]);
            }else{
                $records->whereDate('created_at',$conditions['createdAtDate']);
            }
        }
        if(!empty($conditions['createdAt'])){
            $records = is_array($conditions['createdAt'])?
                $records->whereBetween('created_at', $conditions['createdAt']):
                $records->where('created_at',$conditions['createdAt']);
        }
        if(isset($conditions['status']) && $conditions['status']!='all'){
            if(is_array($conditions['status'])){
                $conditions['status'] = array_filter($conditions['status']);
                //这一层判断必须有，当array_filter是一个空数组
                if(count($conditions['status'])>0){
                    $records = count($conditions['status'])>1?$records->whereIn('status',$conditions['status']):
                        $records->where('status',Arr::first($conditions['status']));
                }
            }
            else{
                if($conditions['status']!=0){
                    $records = $records->where('status',$conditions['status']);
                }

            }
        }
        if(isset($conditions['type']) && $conditions['type']!='all'){
            if(is_array($conditions['type'])){
                $conditions['type'] = array_filter($conditions['type']);
                //这一层判断必须有，当array_filter是一个空数组
                if(count($conditions['type'])>0){
                    $records = count($conditions['type'])>1?$records->whereIn('type',$conditions['type']):
                        $records->where('type',Arr::first($conditions['type']));
                }
            }
            else{
                if($conditions['type']!=0){
                    $records = $records->where('type',$conditions['type']);
                }

            }
        }
        return $records->orderBy($conditions['orderBy']['col'],$conditions['orderBy']['sort']);
    }

    public function getLst(array $conditions=[]) {
        return $this->getRecords($conditions);
    }

    public function getFirstRecord(array $kv,$orderBy=['col'=>'id','sort'=>'desc']){
        $record = $this->newQuery();
        foreach ($kv as $k=>$v) {
            $record = $record->where($k,$v);
        }
        return $record->orderBy($orderBy['col'],$orderBy['sort'])->first();
    }

    public function getRecordById(int $id,array $column = ['*']) {
        return $this->getRecords(compact('id'))->first($column);
    }

    public function getRecordsByIds(array $id,array $column = ['*']) {
        return $this->getRecords(compact('id'))->get($column);
    }

    public function changeColById(int|array $id,array $kv) :int {
        if(!is_array($id)) $id = [$id];
        return $this->changeCol(['id'=>$id], $kv);
    }

    public function changeCol(array $whereKv,array $kv):int {
        $query = $this->newQuery();

        foreach ($whereKv as $k=>$v) {
            if(is_array($v)){
                $query = count($v)>1?$query->whereIn($k,$v):$query->where($k,$v);
            }else{
                $query = $query->where($k,$v);
            }
        }
        return $query->update($kv);
    }

    public function delRecordsById(int|array $id){
        if(!is_array($id)) $id = [$id];
        return $this->delRecords(['id'=>$id]);
    }

    public function delRecords(array $whereKv){
        $query = $this->newQuery();

        foreach ($whereKv as $k=>$v) {

            if(empty($v))continue;

            if(is_array($v)){
                $query = count($v)>1?$query->whereIn($k,$v):$query->where($k,$v);
            }else{
                $query = $query->where($k,$v);
            }
        }
        return $query->delete();
    }
}
